import Vue from 'vue'
import Vuex from 'vuex'
console.log('SRC_STORE: window.electronAPI is:', window.electronAPI);
// const { ipcRenderer } = window.require ? window.require('electron') : { ipcRenderer: null }; // REVERTED (Removed)
const ipcRenderer = window.electronAPI; // Using contextBridge exposed API
// import AppStore from 'electron-store'; // REMOVE: Do not import electron-store directly in renderer with nodeIntegration:false
import { getFormattedDateKey } from '../utils/dateUtils'; // <--- 导入共享函数

Vue.use(Vuex)

// electronStore 实例现在只用于写入，并确保在主进程中也有对应的配置来读取
// 为了写入，我们仍然可以在渲染进程保留一个实例，或者通过 IPC 发送保存请求
// 这里为了简单，写入部分仍然保留在渲染进程，但读取移至主进程。
// const electronStoreWriter = new AppStore({
//   name: 'todo-app-data',
//   schema: {
//     selectedDate: { type: 'string' },
//     savedTodosByDate: {
//       type: 'object',
//       additionalProperties: {
//         type: 'array',
//         items: {
//           type: 'object',
//           properties: {
//             id: { type: 'string' },
//             text: { type: 'string' },
//             completed: { type: 'boolean' },
//             date: { type: 'string' }, // Redundant here, but helps for re-hydration if structure changes
//             createdAt: { type: 'string' },
//             completedDate: { type: ['string', 'null'] },
//             priority: { type: 'number', default: 0 } // New: Priority field
//           },
//           required: ['id', 'text', 'completed', 'createdAt']
//         }
//       }
//     },
//     savedInboxTodos: {
//       type: 'array',
//       items: {
//         type: 'object',
//         properties: {
//           id: { type: 'string' },
//           text: { type: 'string' },
//           completed: { type: 'boolean' },
//           createdAt: { type: 'string' },
//           completedDate: { type: ['string', 'null'] },
//           priority: { type: 'number', default: 0 } // New: Priority field
//         },
//         required: ['id', 'text', 'completed', 'createdAt']
//       }
//     },
//     savedArchivedTodos: {
//        type: 'array',
//         items: {
//           type: 'object',
//           properties: {
//             id: { type: 'string' },
//             text: { type: 'string' },
//             completed: { type: 'boolean' },
//             originalSource: {type: 'string'}, // e.g., 'inbox' or 'date_YYYY-MM-DD'
//             archivedDate: {type: 'string'},
//             completedDate: { type: ['string', 'null'] },
//             priority: { type: 'number', default: 0 } // New: Priority field
//             // Add any other fields that archived todos should have
//           },
//           required: ['id', 'text', 'completed', 'archivedDate']
//         }
//     }
//   },
//   defaults: {
//     selectedDate: getFormattedDateKey(new Date()),
//     savedTodosByDate: {},
//     savedInboxTodos: [],
//     savedArchivedTodos: []
//   }
// });

function debounce(func, delay) {
  let timeout;
  return function(...args) {
    const context = this;
    clearTimeout(timeout);
    timeout = setTimeout(() => func.apply(context, args), delay);
  };
}

// Define a debounced function for saving data to disk via IPC
// This will be initialized after the store is created, so it can access 'store.state' and 'store.dispatch'
let debouncedSaveAllData = null;

const store = new Vuex.Store({
  state: {
    // 初始化时使用默认值，避免阻塞
    currentDate: new Date(), 
    todosByDate: {},
    inboxTodos: [], // 新增：收集箱待办事项
    archivedTodos: [], // 归档待办事项，初始为空
    todayUnarchivedUncompletedCount: 0, // 新增：当天未完成且未归档的待办数量
    inboxUnarchivedUncompletedCount: 0, // 新增：收件箱未完成且未归档的待办数量
    isDataLoaded: false, // 标记核心数据（非归档）是否已从磁盘加载
    archivedTodosLoaded: false, // 新增：标记归档数据是否已加载
    reminders: [], // 新增：提醒列表
    remindersLoaded: false, // 新增：标记提醒数据是否已加载
    settings: { // Initialize settings state
      theme: 'light', // 设置一个备用值，但实际会使用配置文件中的值
      miniMode: false,
      alwaysOnTop: false, // For mini mode
      showCloseDialog: true, // New: Controls if custom close dialog is shown
      closeDialogDefaultAction: 'tray', // New: 'tray' or 'close' - default action if dialog is not shown
      launchOnStartup: false, // <<< NEW: Added launchOnStartup
      // closePreference: 'ask', // Potentially deprecated by new settings
      // dontAskAgainOnClose: false // Potentially deprecated by new settings
    },
    systemThemeListener: null, // Added for system theme listener management
    useSqlite: true, // 新增：标记是否使用SQLite数据库
  },
  mutations: {
    SET_CURRENT_DATE(state, date) {
      state.currentDate = date;
    },
    ADD_TODO(state, { dateKey, todo }) {
      if (!state.todosByDate[dateKey]) {
        Vue.set(state.todosByDate, dateKey, []);
      }
      state.todosByDate[dateKey].push({ ...todo, priority: todo.priority || 0 });
    },
    TOGGLE_TODO(state, { dateKey, todoId }) {
      const todosForDate = state.todosByDate[dateKey];
      const todo = todosForDate ? todosForDate.find(t => t.id === todoId) : null;
      if (todo) {
        todo.completed = !todo.completed;
        todo.completedDate = todo.completed ? new Date().toISOString() : null;
      }
    },
    UPDATE_TODO_TEXT(state, { dateKey, todoId, newText }) {
      const todosForDate = state.todosByDate[dateKey];
      const todo = todosForDate ? todosForDate.find(t => t.id === todoId) : null;
      if (todo) {
        todo.text = newText;
      }
    },
    DELETE_TODO(state, { dateKey, todoId }) {
      if (state.todosByDate[dateKey]) {
        state.todosByDate[dateKey] = state.todosByDate[dateKey].filter(t => t.id !== todoId);
      }
    },
    // SET_HYDRATED_STATE 现在只处理核心数据
    SET_HYDRATED_STATE(state, loadedState) {
      console.log('[Vuex] SET_HYDRATED_STATE: Received loadedState:', loadedState ? JSON.parse(JSON.stringify(loadedState)) : null);
      if (loadedState) {
        // 处理新的计数属性
        state.todayUnarchivedUncompletedCount = loadedState.todayUnarchivedUncompletedCount || 0;
        state.inboxUnarchivedUncompletedCount = loadedState.inboxUnarchivedUncompletedCount || 0;

        // todosByDate, inboxTodos, archivedTodos 会在初始加载时为空，后续按需加载
        state.todosByDate = loadedState.todosByDate || {};
        state.inboxTodos = loadedState.inboxTodos || [];
        state.archivedTodos = loadedState.archivedTodos || []; // 初始为空
        state.archivedTodosLoaded = false; // 明确归档数据未加载
        
        const defaultSettings = {
          theme: 'light',
          miniMode: false,
          alwaysOnTop: false,
          showCloseDialog: true,
          closeDialogDefaultAction: 'tray',
          launchOnStartup: false, // <<< NEW: Default for hydration
        };
        console.log('[Vuex] SET_HYDRATED_STATE: Default application settings:', JSON.parse(JSON.stringify(defaultSettings)));
        console.log('[Vuex] SET_HYDRATED_STATE: Settings from loadedState (before merge):', loadedState.settings ? JSON.parse(JSON.stringify(loadedState.settings)) : null);

        state.settings = { 
          ...defaultSettings, 
          ...(loadedState.settings || {}), 
        };
        console.log('[Vuex] SET_HYDRATED_STATE: Final merged state.settings:', JSON.parse(JSON.stringify(state.settings)));

        state.isDataLoaded = true; // 标记数据已加载（即使部分数据是空的，等待按需填充）
        console.log('[Vuex] Store hydrated with data from disk:', {
          todayUnarchivedUncompletedCount: state.todayUnarchivedUncompletedCount,
          inboxUnarchivedUncompletedCount: state.inboxUnarchivedUncompletedCount,
          todosByDateCount: Object.keys(state.todosByDate).length, // 初始为0
          inboxTodosCount: state.inboxTodos.length, // 初始为0
          archivedTodosCount: state.archivedTodos.length, // 初始为0
          archivedTodosLoaded: state.archivedTodosLoaded,
          settings: state.settings
        });
      } else {
        // Ensure settings have defaults even if no data is loaded (e.g. first run)
        state.settings = {
          theme: 'light',
          miniMode: false,
          alwaysOnTop: false,
          showCloseDialog: true,
          closeDialogDefaultAction: 'tray',
          launchOnStartup: false, // <<< NEW: Default if no loadedState
        };
        state.isDataLoaded = true; // Still hydrated, just with defaults
        console.log('[Vuex] SET_HYDRATED_STATE: No loadedState, initialized with default state.settings:', JSON.parse(JSON.stringify(state.settings)));
      }
    },

    // 新增 Mutation：专门用于设置归档数据
    SET_ARCHIVED_TODOS(state, loadedArchivedTodos) {
      state.archivedTodos = (loadedArchivedTodos || []).map(todo => ({
        ...todo,
        priority: typeof todo.priority === 'number' ? todo.priority : 0,
        completedDate: todo.completedDate || null,
        // Ensure archived specific fields are also mapped if necessary
        originalSource: todo.originalSource,
        archivedDate: todo.archivedDate
      }));
      state.archivedTodosLoaded = true; // 当归档数据实际加载时，设置为true
      console.log('[Vuex] SET_ARCHIVED_TODOS: Archived todos loaded and processed. Count:', state.archivedTodos.length);
    },

    // 新增 Mutation: 按需加载特定日期的数据
    SET_TODOS_FOR_DATE(state, { dateKey, todos }) {
      Vue.set(state.todosByDate, dateKey, todos.map(todo => ({
        ...todo,
        priority: typeof todo.priority === 'number' ? todo.priority : 0,
        completedDate: todo.completedDate || null,
      })));
      console.log(`[Vuex] SET_TODOS_FOR_DATE: Todos for ${dateKey} set. Count: ${todos.length}`);
    },

    // 新增 Mutation: 按需加载收件箱数据
    SET_INBOX_TODOS(state, inboxTodos) {
      state.inboxTodos = (inboxTodos || []).map(todo => ({
        ...todo,
        priority: typeof todo.priority === 'number' ? todo.priority : 0,
        completedDate: todo.completedDate || null,
      }));
      console.log('[Vuex] SET_INBOX_TODOS: Inbox todos set. Count:', state.inboxTodos.length);
    },

    // Mutations for Inbox Todos
    ADD_INBOX_TODO(state, todo) {
      state.inboxTodos.push({ ...todo, priority: todo.priority || 0 });
    },
    TOGGLE_INBOX_TODO(state, todoId) {
      const todo = state.inboxTodos.find(t => t.id === todoId);
      if (todo) {
        todo.completed = !todo.completed;
        todo.completedDate = todo.completed ? new Date().toISOString() : null;
      }
    },
    UPDATE_INBOX_TODO_TEXT(state, { todoId, newText }) {
      const todo = state.inboxTodos.find(t => t.id === todoId);
      if (todo) {
        todo.text = newText;
      }
    },
    DELETE_INBOX_TODO(state, todoId) {
      state.inboxTodos = state.inboxTodos.filter(t => t.id !== todoId);
    },
    // Mutations for Archived Todos
    ADD_TO_ARCHIVE(state, todoToArchive) {
      state.archivedTodos.push({ 
        ...todoToArchive, 
        priority: todoToArchive.priority || 0,
        archivedDate: new Date().toISOString() // Ensure archivedDate is set on archiving
      });
    },
    // --- Batch Mutations ---
    DELETE_BATCH_INBOX_TODOS(state, todoIdsArray) {
      state.inboxTodos = state.inboxTodos.filter(todo => !todoIdsArray.includes(todo.id));
    },
    ADD_BATCH_TO_ARCHIVE(state, archivedItemsArray) {
      state.archivedTodos.push(...archivedItemsArray);
      state.archivedTodosLoaded = true; // Mark as loaded if we add to it
    },
    DELETE_BATCH_TODOS_FROM_DATE(state, { dateKey, todoIdsArray }) {
      console.log(`[Vuex Mutation] DELETE_BATCH_TODOS_FROM_DATE: Called for dateKey: ${dateKey}, todoIds:`, todoIdsArray ? JSON.parse(JSON.stringify(todoIdsArray)) : 'undefined');
      const stateBefore = state.todosByDate[dateKey] ? JSON.parse(JSON.stringify(state.todosByDate[dateKey])) : 'undefined';
      console.log(`[Vuex Mutation] DELETE_BATCH_TODOS_FROM_DATE: State for ${dateKey} BEFORE:`, stateBefore);

      if (state.todosByDate[dateKey]) {
        state.todosByDate[dateKey] = state.todosByDate[dateKey].filter(t => !todoIdsArray.includes(t.id));
        const stateAfter = state.todosByDate[dateKey] ? JSON.parse(JSON.stringify(state.todosByDate[dateKey])) : 'undefined';
        console.log(`[Vuex Mutation] DELETE_BATCH_TODOS_FROM_DATE: State for ${dateKey} AFTER:`, stateAfter);
      } else {
        console.warn(`[Vuex Mutation] DELETE_BATCH_TODOS_FROM_DATE: No todos found for dateKey ${dateKey} to delete from.`);
      }
    },
    DELETE_ARCHIVED_TODOS_BATCH(state, todoIdsArray) {
      state.archivedTodos = state.archivedTodos.filter(todo => !todoIdsArray.includes(todo.id));
    },
    // New Mutations for Priority
    UPDATE_TODO_PRIORITY(state, { todoId, priority, dateKey }) {
      if (dateKey) {
        const todosForDate = state.todosByDate[dateKey] || [];
        const todoIndex = todosForDate.findIndex(t => t.id === todoId);
        if (todoIndex !== -1) {
          Vue.set(todosForDate[todoIndex], 'priority', priority);
        }
      }
    },
    UPDATE_INBOX_TODO_PRIORITY(state, { todoId, priority }) {
      const todoIndex = state.inboxTodos.findIndex(t => t.id === todoId);
      if (todoIndex !== -1) {
        Vue.set(state.inboxTodos[todoIndex], 'priority', priority); 
      }
    },
    MOVE_INBOX_TODO_TO_DATE(state, { todoToMove, dateKey }) {
      if (!todoToMove) {
        console.warn(`[Vuex Store] MOVE_INBOX_TODO_TO_DATE: todoToMove is undefined.`);
        return;
      }
      // 1. Add to the target date in todosByDate
      if (!state.todosByDate[dateKey]) {
        Vue.set(state.todosByDate, dateKey, []);
      }
      // Ensure all properties are carried over, including priority
      state.todosByDate[dateKey].push({
        ...todoToMove,
        priority: typeof todoToMove.priority === 'number' ? todoToMove.priority : 0,
      });

      // 2. Remove from inboxTodos
      state.inboxTodos = state.inboxTodos.filter(t => t.id !== todoToMove.id);
      console.log(`[Vuex Store] MOVE_INBOX_TODO_TO_DATE: Moved todo ${todoToMove.id} to ${dateKey}. Inbox count: ${state.inboxTodos.length}, Target date count: ${state.todosByDate[dateKey].length}`);
    },
    MOVE_TODO_TO_DATE(state, { todoId, originalDateKey, newDateKey, todoToMove }) {
      if (originalDateKey === newDateKey) return;
      if (!todoToMove) {
        console.warn(`[Vuex Store] MOVE_TODO_TO_DATE: todoToMove is undefined. Original todoId: ${todoId}`);
        return;
      }
      console.log(`[Vuex Store] MOVE_TODO_TO_DATE: Moving todoId ${todoId} from ${originalDateKey} to ${newDateKey}. Todo data:`, JSON.parse(JSON.stringify(todoToMove)));

      // Add to new dateKey
      if (!state.todosByDate[newDateKey]) {
        Vue.set(state.todosByDate, newDateKey, []); // Ensure reactivity for new date
      }
      state.todosByDate[newDateKey].push(todoToMove);
      
      // Remove from original dateKey
      if (state.todosByDate[originalDateKey]) {
        state.todosByDate[originalDateKey] = state.todosByDate[originalDateKey].filter(t => t.id !== todoId);
        console.log(`[Vuex Store] MOVE_TODO_TO_DATE: Removed todo ${todoId} from ${originalDateKey}. Count for original: ${state.todosByDate[originalDateKey].length}`);
      } else {
        console.warn(`[Vuex Store] MOVE_TODO_TO_DATE: originalDateKey ${originalDateKey} not found in todosByDate when trying to remove todo ${todoId}.`);
      }
      console.log(`[Vuex Store] MOVE_TODO_TO_DATE: Added todo ${todoId} to ${newDateKey}. Count for new: ${state.todosByDate[newDateKey].length}`);
      // Optional: Sort todos if needed, e.g., by creation time or priority
      // state.todosByDate[newDateKey].sort((a, b) => a.createdAt - b.createdAt); 
    },
    SET_DATA_LOADED_STATUS(state, status) {
      state.isDataLoaded = status;
    },
    // Mutation for settings - RENAMED AND SIMPLIFIED
    UPDATE_SETTINGS_STATE_MUTATION(state, newSettings) { // RENAMED from UPDATE_SETTINGS
      console.log('[Vuex] UPDATE_SETTINGS_STATE_MUTATION 当前设置:', JSON.parse(JSON.stringify(state.settings)));
      console.log('[Vuex] UPDATE_SETTINGS_STATE_MUTATION 接收到新设置:', JSON.parse(JSON.stringify(newSettings)));
      
      // 确保所有设置字段都被保留
      state.settings = {
        ...state.settings, // 保留现有设置
        ...newSettings, // 使用新设置覆盖
      };
      
      console.log('[Vuex] UPDATE_SETTINGS_STATE_MUTATION 更新后设置:', JSON.parse(JSON.stringify(state.settings)));
      
      // 触发保存
      if (debouncedSaveAllData) {
        debouncedSaveAllData();
      }
    },
    SET_SYSTEM_THEME_LISTENER(state, listener) {
      state.systemThemeListener = listener;
    },
    SET_REMINDERS(state, reminders) {
      state.reminders = reminders;
      state.remindersLoaded = true;
    },
    ADD_REMINDER(state, reminder) {
      state.reminders.push(reminder);
    },
    UPDATE_REMINDER(state, updatedReminder) {
      const index = state.reminders.findIndex(r => r.id === updatedReminder.id);
      if (index !== -1) {
        Vue.set(state.reminders, index, updatedReminder);
      }
    },
    DELETE_REMINDER(state, reminderId) {
      state.reminders = state.reminders.filter(r => r.id !== reminderId);
    },
    SET_REMINDER_ACTIVE_STATUS(state, { reminderId, isActive }) {
      const reminder = state.reminders.find(r => r.id === reminderId);
      if (reminder) {
        reminder.isActive = isActive;
      }
    },
  },
  actions: {
    // Centralized data saving action
    async saveAllDataToDisk({ state }) {
      if (!ipcRenderer) return;
      try {
        const dataToSave = {
          todosByDate: state.todosByDate,
          inboxTodos: state.inboxTodos,
          archivedTodos: state.archivedTodos,
          settings: state.settings
        };
        // console.log('[Vuex] Sending data to save:', dataToSave);
        ipcRenderer.send('save-app-data', dataToSave);
        } catch (error) {
        console.error('[Vuex] Error sending data to save:', error);
      }
    },
    
    // 新增：加载所有数据（从SQLite）
    async loadAllDataFromSqlite({ commit }) {
      try {
        console.log('[Vuex] 从SQLite加载所有数据');
        const data = await ipcRenderer.db.loadAllData();
        
        if (data) {
          commit('SET_HYDRATED_STATE', data);
          return true;
        } else {
          console.error('[Vuex] 从SQLite加载数据失败');
          return false;
        }
      } catch (error) {
        console.error('[Vuex] 从SQLite加载数据出错:', error);
        return false;
      }
    },
    
    // 修改：加载初始数据时首先尝试使用SQLite
    async loadInitialDataFromDisk({ commit, dispatch, state }) {
      console.log("[Vuex Store] 尝试加载初始数据...");
      
      let dataLoaded = false;
      let configTheme = null;
      
      // 首先尝试从主进程获取配置文件中的主题设置
      try {
        const configData = await ipcRenderer.invoke('load-app-data');
        if (configData && configData.settings && configData.settings.theme) {
          configTheme = configData.settings.theme;
          console.log(`[Vuex Store] 从配置文件获取到主题设置: ${configTheme}`);
        }
      } catch (error) {
        console.error("[Vuex Store] 获取配置文件主题设置失败:", error);
      }
      
      // 如果设置为使用SQLite，则尝试使用SQLite加载数据
      if (state.useSqlite) {
        try {
          dataLoaded = await dispatch('loadAllDataFromSqlite');
        } catch (error) {
          console.error("[Vuex Store] 从SQLite加载数据失败:", error);
          dataLoaded = false;
        }
      }
      
      // 如果SQLite加载失败，回退到electron-store
      if (!dataLoaded) {
        try {
          const data = await ipcRenderer.invoke('load-app-data');
          console.log("[Vuex Store] 从主进程接收数据:", data ? JSON.parse(JSON.stringify(data)) : null);
          
          if (data) {
            commit('SET_HYDRATED_STATE', data); 
            dataLoaded = true;
          } else {
            console.log("[Vuex Store] 主进程未返回数据。使用默认值初始化。");
            commit('SET_HYDRATED_STATE', {}); // 使用空对象进行初始化
            dataLoaded = true; // 虽然没有数据，但也算加载完成
          }
        } catch (error) {
          console.error("[Vuex Store] 从electron-store加载数据出错:", error);
          commit('SET_HYDRATED_STATE', {}); // 发生错误时也使用空对象初始化
          dataLoaded = true; // 虽然出错，但也算加载完成
        }
      }
      
      // 如果从配置文件获取到了主题设置，优先使用它
      if (configTheme) {
        console.log(`[Vuex Store] 使用配置文件中的主题设置: ${configTheme}`);
        // 更新状态中的主题设置
        commit('UPDATE_SETTINGS_STATE_MUTATION', { theme: configTheme });
        // 应用主题
        await dispatch('applyTheme', configTheme);
      } else if (state.settings && typeof state.settings.theme === 'string') {
        // 否则使用状态中的主题设置
        console.log(`[Vuex Store] 使用状态中的主题设置: ${state.settings.theme}`);
        await dispatch('applyTheme', state.settings.theme);
      }
      
      return dataLoaded;
    },
    
    // 修改：从electron-store迁移到SQLite
    async migrateToSqlite({ dispatch, state }) {
      try {
        console.log('[Vuex] 开始从electron-store迁移数据到SQLite');
        const result = await ipcRenderer.db.migrateFromStore();
        
        if (result) {
          console.log('[Vuex] 数据迁移成功');
          // 重新加载数据以确保正确同步
          await dispatch('loadAllDataFromSqlite');
          return true;
        } else {
          console.error('[Vuex] 数据迁移失败');
          return false;
        }
      } catch (error) {
        console.error('[Vuex] 数据迁移出错:', error);
        return false;
      }
    },
    
    // 修改：添加待办事项，使用SQLite API
    async addTodo({ commit, getters, dispatch, state }, text) {
      if (!text.trim()) return;
      
      const todo = {
        id: Date.now().toString(),
        text: text.trim(),
        completed: false,
        createdAt: new Date().toISOString(),
        completedDate: null,
        priority: 0
      };
      
      // 同时提交到Vuex状态和数据库
      const dateKey = getters.formattedCurrentDateKey;
      commit('ADD_TODO', { dateKey, todo });
      
      if (state.useSqlite) {
        await ipcRenderer.db.addTodoToDate(todo, dateKey);
      }
      
      dispatch('triggerSaveData');
    },
    
    // 修改：切换待办事项完成状态
    async toggleTodo({ commit, getters, state, dispatch }, todoId) {
      const dateKey = getters.formattedCurrentDateKey;
      const todosForDate = state.todosByDate[dateKey] || [];
      const todo = todosForDate.find(t => t.id === todoId);
      
      if (!todo) return;
      
      // 更新前先保存原始状态，以便SQLite操作
      const originalStatus = todo.completed;
      
      // 同时提交到Vuex状态
      commit('TOGGLE_TODO', { dateKey, todoId });
      
      // 获取更新后的待办事项
      const updatedTodo = state.todosByDate[dateKey].find(t => t.id === todoId);
      
      if (state.useSqlite && updatedTodo) {
        await ipcRenderer.db.updateTodo(updatedTodo);
      }
      
      dispatch('triggerSaveData');
    },
    
    // 修改：更新待办事项文本
    async updateTodoText({ commit, state, dispatch }, { todoId, newText, dateKey }) {
      const todosForDate = state.todosByDate[dateKey] || [];
      const todo = todosForDate.find(t => t.id === todoId);
      
      if (!todo || !newText.trim()) return;
      
      // 同时提交到Vuex状态
      commit('UPDATE_TODO_TEXT', { dateKey, todoId, newText: newText.trim() });
      
      // 获取更新后的待办事项
      const updatedTodo = state.todosByDate[dateKey].find(t => t.id === todoId);
      
      if (state.useSqlite && updatedTodo) {
        await ipcRenderer.db.updateTodo(updatedTodo);
      }
      
      dispatch('triggerSaveData');
    },
    
    // 修改：删除待办事项
    async deleteTodo({ commit, state, dispatch }, { todoId, dateKey }) {
      // 同时从Vuex状态删除
      commit('DELETE_TODO', { dateKey, todoId });
      
      if (state.useSqlite) {
        await ipcRenderer.db.deleteTodoFromDate(todoId, dateKey);
      }
      
      dispatch('triggerSaveData');
    },
    
    // 修改：添加收件箱待办事项
    async addInboxTodo({ commit, dispatch, state }, text) {
      if (!text.trim()) return;
      
      const todo = {
        id: Date.now().toString(),
        text: text.trim(),
        completed: false,
        createdAt: new Date().toISOString(),
        completedDate: null,
        priority: 0
      };
      
      // 同时提交到Vuex状态
      commit('ADD_INBOX_TODO', todo);
      
      if (state.useSqlite) {
        await ipcRenderer.db.addInboxTodo(todo);
      }
      
      dispatch('triggerSaveData');
    },
    
    // 修改：切换收件箱待办事项完成状态
    async toggleInboxTodo({ commit, dispatch, state }, todoId) {
      const todo = state.inboxTodos.find(t => t.id === todoId);
      
      if (!todo) return;
      
      // 更新前先保存原始状态，以便SQLite操作
      const originalStatus = todo.completed;
      
      // 同时提交到Vuex状态
      commit('TOGGLE_INBOX_TODO', todoId);
      
      // 获取更新后的待办事项
      const updatedTodo = state.inboxTodos.find(t => t.id === todoId);
      
      if (state.useSqlite && updatedTodo) {
        await ipcRenderer.db.updateTodo(updatedTodo);
      }
      
      dispatch('triggerSaveData');
    },
    
    // 修改：更新收件箱待办事项文本
    async updateInboxTodoText({ commit, dispatch, state }, { todoId, newText }) {
      const todo = state.inboxTodos.find(t => t.id === todoId);
      
      if (!todo || !newText.trim()) return;
      
      // 同时提交到Vuex状态
      commit('UPDATE_INBOX_TODO_TEXT', { todoId, newText: newText.trim() });
      
      // 获取更新后的待办事项
      const updatedTodo = state.inboxTodos.find(t => t.id === todoId);
      
      if (state.useSqlite && updatedTodo) {
        await ipcRenderer.db.updateTodo(updatedTodo);
      }
      
      dispatch('triggerSaveData');
    },
    
    // 修改：删除收件箱待办事项
    async deleteInboxTodo({ commit, dispatch, state }, todoId) {
      // 同时从Vuex状态删除
      commit('DELETE_INBOX_TODO', todoId);
      
      if (state.useSqlite) {
        await ipcRenderer.db.deleteInboxTodo(todoId);
      }
      
      dispatch('triggerSaveData');
    },
    
    // 添加: 归档收件箱待办事项
    async archiveInboxTodo({ commit, dispatch, state }, { todoId }) {
      const todo = state.inboxTodos.find(t => t.id === todoId);
      if (!todo) return;
      
      console.log(`[Vuex] 归档收件箱待办事项: ${todoId}`);
      // 调用通用归档方法
      await dispatch('archiveTodo', { todo, originalSource: 'inbox' });
    },
    
    // 修改：归档待办事项
    async archiveTodo({ commit, dispatch, state }, { todo, originalSource }) {
      console.log(`[Vuex] 开始归档待办事项: id=${todo.id}, originalSource=${originalSource}`);
      
      // 首先提交到归档状态
      commit('ADD_TO_ARCHIVE', { ...todo, originalSource, archivedDate: new Date().toISOString() });
      console.log(`[Vuex] 待办事项已添加到归档状态`);
      
      // 然后更新数据库
      let dbSuccess = true;
      if (state.useSqlite) {
        try {
          console.log(`[Vuex] 调用数据库归档方法`);
          dbSuccess = await ipcRenderer.db.archiveTodo(todo, originalSource);
          console.log(`[Vuex] 数据库归档结果: ${dbSuccess ? '成功' : '失败'}`);
        } catch (error) {
          console.error(`[Vuex] 数据库归档操作出错:`, error);
          dbSuccess = false;
        }
      }
      
      // 最后从原始位置删除
      if (originalSource === 'inbox') {
        console.log(`[Vuex] 从收件箱移除待办事项: ${todo.id}`);
        commit('DELETE_INBOX_TODO', todo.id);
      } else {
        console.log(`[Vuex] 从日期 ${originalSource} 移除待办事项: ${todo.id}`);
        const dateKey = originalSource;
        commit('DELETE_TODO', { dateKey, todoId: todo.id });
      }
      
      dispatch('triggerSaveData');
      console.log(`[Vuex] 归档操作完成: id=${todo.id}`);
      
      return dbSuccess;
    },
    
    // 修改：批量归档待办事项
    async archiveBatchTodos({ commit, state, dispatch }, { todoIds, source, dateKeyIfFromDate }){
      if (!todoIds.length) {
        console.log('[Vuex] 批量归档: 没有提供待办事项ID，操作取消');
        return false;
      }
      
      console.log(`[Vuex] 开始批量归档: 来源=${source}, 日期=${dateKeyIfFromDate || '无'}, ID数量=${todoIds.length}`);
      
      let todosToArchive = [];
      if (source === 'inbox') {
        todosToArchive = state.inboxTodos.filter(todo => todoIds.includes(todo.id));
        console.log(`[Vuex] 从收件箱中找到 ${todosToArchive.length} 个待归档项 (从 ${todoIds.length} 个ID中)`);
      } else if (source === 'date') {
        todosToArchive = (state.todosByDate[dateKeyIfFromDate] || []).filter(todo => todoIds.includes(todo.id));
        console.log(`[Vuex] 从日期 ${dateKeyIfFromDate} 中找到 ${todosToArchive.length} 个待归档项 (从 ${todoIds.length} 个ID中)`);
      }
      
      if (!todosToArchive.length) {
        console.log('[Vuex] 批量归档: 没有找到匹配的待办事项，操作取消');
        return false;
      }
      
      // 添加归档信息
      const archivedItems = todosToArchive.map(todo => ({
        ...todo,
        originalSource: source === 'inbox' ? 'inbox' : dateKeyIfFromDate,
        archivedDate: new Date().toISOString()
      }));
      
      // 首先提交到Vuex状态
      commit('ADD_BATCH_TO_ARCHIVE', archivedItems);
      console.log(`[Vuex] ${archivedItems.length} 个待办事项已批量添加到归档状态`);
      
      // 然后更新数据库
      let dbSuccess = true;
      if (state.useSqlite) {
        try {
          console.log('[Vuex] 调用数据库批量归档方法');
          dbSuccess = await ipcRenderer.db.archiveBatchTodos(todosToArchive, source === 'inbox' ? 'inbox' : dateKeyIfFromDate);
          console.log(`[Vuex] 数据库批量归档结果: ${dbSuccess ? '成功' : '失败'}`);
        } catch (error) {
          console.error('[Vuex] 数据库批量归档操作出错:', error);
          dbSuccess = false;
        }
      }
      
      // 最后从原始位置删除
      if (source === 'inbox') {
        console.log(`[Vuex] 从收件箱批量移除 ${todoIds.length} 个待办事项`);
        commit('DELETE_BATCH_INBOX_TODOS', todoIds);
      } else {
        console.log(`[Vuex] 从日期 ${dateKeyIfFromDate} 批量移除 ${todoIds.length} 个待办事项`);
        commit('DELETE_BATCH_TODOS_FROM_DATE', { dateKey: dateKeyIfFromDate, todoIdsArray: todoIds });
      }
      
      dispatch('triggerSaveData');
      console.log(`[Vuex] 批量归档操作完成，处理了 ${todosToArchive.length} 个待办事项`);
      
      return dbSuccess;
    },
    
    // 新增 Action：处理从特定日期批量删除待办事项的逻辑
    async deleteBatchTodosFromDate({ commit, dispatch, state }, { dateKey, todoIdsArray }) {
      if (!todoIdsArray || todoIdsArray.length === 0) {
        console.warn('[Vuex Action] deleteBatchTodosFromDate: todoIdsArray is empty or undefined.');
        return false;
      }
      console.log(`[Vuex Action] deleteBatchTodosFromDate: Called for dateKey: ${dateKey}, todoIds:`, JSON.parse(JSON.stringify(todoIdsArray)));
      
      try {
        let successInDb = true;
        if (state.useSqlite) {
          successInDb = await ipcRenderer.db.deleteBatchTodosFromDate(todoIdsArray, dateKey);
          console.log(`[Vuex Action] deleteBatchTodosFromDate: DB deletion result: ${successInDb}`);
        }
        
        if (successInDb) {
          commit('DELETE_BATCH_TODOS_FROM_DATE', { dateKey, todoIdsArray });
          dispatch('triggerSaveData');
          return true;
        } else {
          console.error('[Vuex Action] deleteBatchTodosFromDate: Failed to delete from database.');
          return false;
        }
      } catch (error) {
        console.error('[Vuex Action] deleteBatchTodosFromDate: Error during operation:', error);
        return false;
      }
    },
    
    // 新增 Action: 处理从收件箱批量删除待办事项的逻辑
    async deleteBatchInboxTodos({ commit, dispatch, state }, todoIdsArray) {
      if (!todoIdsArray || todoIdsArray.length === 0) {
        console.warn('[Vuex Action] deleteBatchInboxTodos: todoIdsArray is empty or undefined.');
        return false;
      }
      console.log(`[Vuex Action] deleteBatchInboxTodos: Called for todoIds:`, JSON.parse(JSON.stringify(todoIdsArray)));

      try {
        let successInDb = true;
        if (state.useSqlite) {
          // 注意：需要确保 db.js 中有 deleteBatchInboxTodos 方法
          successInDb = await ipcRenderer.db.deleteBatchInboxTodos(todoIdsArray);
          console.log(`[Vuex Action] deleteBatchInboxTodos: DB deletion result: ${successInDb}`);
        }

        if (successInDb) {
          commit('DELETE_BATCH_INBOX_TODOS', todoIdsArray);
          dispatch('triggerSaveData');
          return true;
        } else {
          console.error('[Vuex Action] deleteBatchInboxTodos: Failed to delete from database.');
          return false;
        }
      } catch (error) {
        console.error('[Vuex Action] deleteBatchInboxTodos: Error during operation:', error);
        return false;
      }
    },
    
    // 修改：删除归档待办事项
    async deleteArchivedTodosBatch({ commit, dispatch, state }, todoIdsArray) {
      // 同时从Vuex状态删除
      commit('DELETE_ARCHIVED_TODOS_BATCH', todoIdsArray);
      
      if (state.useSqlite) {
        await ipcRenderer.db.deleteArchivedBatchTodos(todoIdsArray);
      }
      
      dispatch('triggerSaveData');
    },
    
    // 修改：更新待办事项优先级
    async updateTodoPriority({ commit, state, dispatch, getters }, { todoId, priority, dateKey, source }){
      console.log(`[Vuex] updateTodoPriority被调用: todoId=${todoId}, priority=${priority}, dateKey=${dateKey}, source=${source}`);
      
      if (typeof priority !== 'number' || priority < 0 || priority > 3) {
        console.error('[Vuex] Invalid priority value:', priority);
        return;
      }
      
      if (source === 'inbox') {
        const todo = state.inboxTodos.find(t => t.id === todoId);
        if (!todo) {
          console.error('[Vuex] Could not find todo with ID', todoId, 'in inbox');
          return;
        }
        
        console.log('[Vuex] 更新收件箱待办事项优先级:', todoId, priority);
        // 更新Vuex状态
        commit('UPDATE_INBOX_TODO_PRIORITY', { todoId, priority });
        
        // 获取更新后的待办事项
        const updatedTodo = state.inboxTodos.find(t => t.id === todoId);
        
        if (state.useSqlite && updatedTodo) {
          console.log('[Vuex] 使用SQLite API更新待办优先级:', updatedTodo);
          await ipcRenderer.db.updateTodo(updatedTodo);
        }
        
      } else if (source === 'date' || !source) { // 如果source未指定，默认为date
        // 如果没有提供dateKey，尝试从state.todosByDate中查找
        if (!dateKey) {
          console.log('[Vuex] dateKey未提供，尝试从所有日期中查找待办事项');
          let foundDateKey = null;
          let foundTodo = null;
          
          // 遍历所有日期查找匹配的todoId
          for (const key in state.todosByDate) {
            const todo = state.todosByDate[key].find(t => t.id === todoId);
            if (todo) {
              foundDateKey = key;
              foundTodo = todo;
              break;
            }
          }
          
          if (foundDateKey) {
            dateKey = foundDateKey;
            console.log('[Vuex] 找到待办事项所属日期:', dateKey);
          } else {
            console.error('[Vuex] 无法确定待办事项所属日期:', todoId);
            return;
          }
        }
        
        const dateTodos = state.todosByDate[dateKey] || [];
        const todo = dateTodos.find(t => t.id === todoId);
        if (!todo) {
          console.error('[Vuex] Could not find todo with ID', todoId, 'for date', dateKey);
          return;
        }
        
        console.log('[Vuex] 更新日期待办事项优先级:', todoId, priority, dateKey);
        // 更新Vuex状态
        commit('UPDATE_TODO_PRIORITY', { todoId, priority, dateKey });
        
        // 获取更新后的待办事项
        const updatedTodo = (state.todosByDate[dateKey] || []).find(t => t.id === todoId);
        
        if (state.useSqlite && updatedTodo) {
          console.log('[Vuex] 使用SQLite API更新待办优先级:', updatedTodo);
          await ipcRenderer.db.updateTodo(updatedTodo);
        }
      } else {
        console.error('[Vuex] 未知的source类型:', source);
        return;
      }
      
      console.log('[Vuex] 优先级更新完成, 触发保存');
      dispatch('triggerSaveData');
    },
    
    // 修改：移动收件箱待办事项到日期
    async moveInboxTodoToDate({ commit, state, dispatch }, { todoId, date }) {
      const todoToMove = state.inboxTodos.find(t => t.id === todoId);
      if (!todoToMove) return;
      
      const dateKey = typeof date === 'string' ? date : getFormattedDateKey(date);
      
      // 更新Vuex状态
      commit('MOVE_INBOX_TODO_TO_DATE', { todoToMove, dateKey });
      
      if (state.useSqlite) {
        await ipcRenderer.db.moveTodoToDate(todoId, dateKey);
      }
      
      dispatch('triggerSaveData');
    },
    
    // 修改：从一个日期移动待办事项到另一个日期
    async moveTodoToDate({ commit, state, dispatch }, { todoId, originalDateKey, newDate }) {
      const todos = state.todosByDate[originalDateKey] || [];
      const todoToMove = todos.find(t => t.id === todoId);
      if (!todoToMove) return;
      
      const newDateKey = typeof newDate === 'string' ? newDate : getFormattedDateKey(newDate);
      
      // 更新Vuex状态
      commit('MOVE_TODO_TO_DATE', { todoId, originalDateKey, newDateKey, todoToMove });
      
      if (state.useSqlite) {
        await ipcRenderer.db.moveTodoToDate(todoId, newDateKey);
      }
      
      dispatch('triggerSaveData');
    },
    
    // 添加: 从日期归档待办事项
    async archiveTodoFromDate({ commit, dispatch, state }, { todoId, dateKey }) {
      console.log(`[Vuex] 开始从日期 ${dateKey} 归档待办事项: ${todoId}`);
      
      // 查找待办事项
      const todos = state.todosByDate[dateKey] || [];
      const todo = todos.find(t => t.id === todoId);
      
      if (!todo) {
        console.error(`[Vuex] 无法找到待归档的待办事项: ${todoId} 在日期 ${dateKey}`);
        return false;
      }
      
      console.log(`[Vuex] 找到待归档的待办事项:`, todo);
      
      // 调用通用归档方法，传递原始来源为日期键
      return await dispatch('archiveTodo', { todo, originalSource: dateKey });
    },
    
    // 修改：更新设置
    async updateSettings({ commit, dispatch }, settingsPayload) {
      // 更新Vuex状态
      commit('UPDATE_SETTINGS_STATE_MUTATION', settingsPayload);
      
      if (settingsPayload.theme) {
        await dispatch('applyTheme', settingsPayload.theme);
      }
      
      if (typeof settingsPayload.alwaysOnTop !== 'undefined' && ipcRenderer) {
        console.log(`[Vuex] Sending always-on-top request: ${settingsPayload.alwaysOnTop}`);
        ipcRenderer.send('set-always-on-top', settingsPayload.alwaysOnTop);
      }
      
      dispatch('triggerSaveData');
    },
    
    // 添加缺少的action: triggerSaveData
    triggerSaveData({ dispatch }) {
      console.log('[Vuex] triggerSaveData called, debouncing save operation');
      if (debouncedSaveAllData) {
        debouncedSaveAllData();
      } else {
        // 如果debounced函数未初始化，直接保存
        dispatch('saveAllDataToDisk');
      }
    },
    
    // 添加缺少的action: applyTheme
    async applyTheme({ state }, themeName) {
      console.log('[Vuex] applyTheme called with theme:', themeName);
      
      // 确保总是有一个有效的主题
      if (!themeName) {
        themeName = 'light'; // 使用light作为备用主题
        console.log('[Vuex] 使用备用主题: light');
      }
      
      let themeToApply = themeName;
      if (themeName === 'system') {
        // 检查系统主题
        const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
        themeToApply = prefersDark ? 'dark' : 'light';
        
        // 设置系统主题监听器，如果尚未设置
        if (!state.systemThemeListener && window.matchMedia) {
          const systemThemeChangeHandler = (e) => {
            const newTheme = e.matches ? 'dark' : 'light';
            document.documentElement.setAttribute('data-theme', newTheme);
            document.documentElement.classList.remove('light-theme', 'dark-theme');
            document.documentElement.classList.add(`${newTheme}-theme`);
            console.log('[Vuex Store] System theme changed to:', newTheme);
          };
          
          const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)');
          mediaQuery.addEventListener('change', systemThemeChangeHandler);
          
          // 保存引用以便我们将来可以移除监听器
          this.commit('SET_SYSTEM_THEME_LISTENER', systemThemeChangeHandler);
        }
      }
      
      // 应用主题
      document.documentElement.setAttribute('data-theme', themeToApply);
      
      // 同时更新classList以确保CSS选择器生效
      document.documentElement.classList.remove('light-theme', 'dark-theme');
      document.documentElement.classList.add(`${themeToApply}-theme`);
      
      console.log(`[Vuex] Applied explicit ${themeToApply}-theme`);
      
      return themeToApply; // Return the actually applied theme
    },
    
    // 添加nextDay action
    nextDay({ commit, state }) {
      const nextDate = new Date(state.currentDate);
      nextDate.setDate(nextDate.getDate() + 1);
      commit('SET_CURRENT_DATE', nextDate);
    },
    
    // 添加previousDay action
    previousDay({ commit, state }) {
      const previousDate = new Date(state.currentDate);
      previousDate.setDate(previousDate.getDate() - 1);
      commit('SET_CURRENT_DATE', previousDate);
    },
    
    // 添加updateSettingsInternal action，供应用内部组件使用
    updateSettingsInternal({ commit, dispatch }, settingsPayload) {
      commit('UPDATE_SETTINGS_STATE_MUTATION', settingsPayload);
      
      if (settingsPayload.theme) {
        dispatch('applyTheme', settingsPayload.theme);
      }
      
      if (typeof settingsPayload.alwaysOnTop !== 'undefined' && ipcRenderer) {
        console.log(`[Vuex] Sending always-on-top request: ${settingsPayload.alwaysOnTop}`);
        ipcRenderer.send('set-always-on-top', settingsPayload.alwaysOnTop);
      }
      
      dispatch('triggerSaveData');
    },
    
    // 新增 Action: 按需加载特定日期的数据
    async fetchTodosForDate({ commit, state }, dateKey) {
      // 防止重复加载，可以根据需要添加更复杂的逻辑，例如检查数据是否已存在且未过期
      // if (state.todosByDate[dateKey] && state.todosByDate[dateKey].length > 0) {
      //   console.log(`[Vuex] Todos for ${dateKey} already loaded.`);
      //   return;
      // }
      console.log(`[Vuex] Fetching todos for date: ${dateKey}`);
      try {
        const todos = await ipcRenderer.db.getTodosForDateKey(dateKey);
        commit('SET_TODOS_FOR_DATE', { dateKey, todos });
        console.log(`[Vuex] Successfully fetched and set todos for ${dateKey}. Count: ${todos.length}`);
      } catch (error) {
        console.error(`[Vuex] Error fetching todos for date ${dateKey}:`, error);
        // 可以考虑提交一个错误状态或通知用户
      }
    },

    // 新增 Action: 按需加载收件箱数据
    async fetchInboxTodos({ commit, state }) {
      // if (state.inboxTodos && state.inboxTodos.length > 0 && !NEEDS_REFRESH) { // 简单的缓存逻辑
      //   console.log(\'[Vuex] Inbox todos already loaded.\');
      //   return;
      // }
      console.log('[Vuex] Fetching inbox todos...');
      try {
        const inboxTodos = await ipcRenderer.db.getInboxTodos();
        commit('SET_INBOX_TODOS', inboxTodos);
        console.log('[Vuex] Successfully fetched and set inbox todos. Count:', inboxTodos.length);
      } catch (error) {
        console.error('[Vuex] Error fetching inbox todos:', error);
      }
    },

    // 修改 fetchArchivedTodosFromDisk action 以确保它从SQLite加载
    async fetchArchivedTodosFromDisk({ commit, state }) {
      if (state.archivedTodosLoaded) {
        console.log('[Vuex] Archived todos already loaded.');
        return;
      }
      console.log('[Vuex] Fetching archived todos from disk (SQLite)...');
      try {
        let archivedTodos = [];
        if (state.useSqlite) { // 优先从SQLite加载
          archivedTodos = await ipcRenderer.db.getArchivedTodos();
          console.log('[Vuex] Archived todos fetched from SQLite. Count:', archivedTodos.length);
        } else {
          // 如果未使用SQLite (理论上已迁移，但保留回退逻辑以防万一)
          // 这个分支可能需要从 electron-store 加载，但目前 db.js 的 loadAllData 不再返回此数据
          // 为了简单起见，如果未使用SQLite，我们假设归档数据为空或需要其他机制加载
          console.warn('[Vuex] fetchArchivedTodosFromDisk: Not using SQLite, and electron-store direct load for archives is not implemented here. Returning empty.');
        }
        commit('SET_ARCHIVED_TODOS', archivedTodos);
      } catch (error) {
        console.error('[Vuex] Error fetching archived todos from disk:', error);
        commit('SET_ARCHIVED_TODOS', []); // 出错时设置为空数组
      }
    },

    // 新增 Action: 添加待办事项到特定日期 (主要供 CalendarView 使用)
    async addTodoToDate({ commit, dispatch, state }, { text, date, priority = 0 }) { // priority default to 0 (PRIORITIES.NONE)
      if (!text || !text.trim() || !date) {
        console.error('[Vuex Action] addTodoToDate: Text or date is missing.', { text, date });
        return;
      }

      const dateKey = getFormattedDateKey(date); // Ensure date is converted to YYYY-MM-DD key
      const newTodo = {
        id: Date.now().toString(),
        text: text.trim(),
        completed: false,
        createdAt: new Date().toISOString(),
        completedDate: null,
        priority: priority, // Use provided priority or default
        date: dateKey,      // Store the dateKey with the todo
        source: 'date'      // Indicate it belongs to a date
      };

      console.log(`[Vuex Action] addTodoToDate: Adding todo to dateKey: ${dateKey}`, newTodo);

      try {
        let successInDb = true;
        if (state.useSqlite) {
          successInDb = await ipcRenderer.db.addTodoToDate(newTodo, dateKey);
          console.log(`[Vuex Action] addTodoToDate: DB add result: ${successInDb}`);
        }

        if (successInDb) {
          commit('ADD_TODO', { dateKey, todo: newTodo }); // Use the existing ADD_TODO mutation
          dispatch('triggerSaveData');
        } else {
          console.error('[Vuex Action] addTodoToDate: Failed to add todo to database.');
        }
      } catch (error) {
        console.error('[Vuex Action] addTodoToDate: Error during operation:', error);
      }
    },

    async fetchAllReminders({ commit, state }) {
      try {
        // 如果没有ipcRenderer或者没有db-get-all-reminders方法，返回空数组
        if (!ipcRenderer || !ipcRenderer.invoke) {
          console.warn('[Vuex] fetchAllReminders: ipcRenderer not available');
          commit('SET_REMINDERS', []);
          return [];
        }
        
        const reminders = await ipcRenderer.invoke('db-get-all-reminders');
        commit('SET_REMINDERS', reminders || []);
        console.log('[Vuex] fetchAllReminders: Loaded reminders:', reminders ? reminders.length : 0);
        return reminders;
      } catch (error) {
        console.error('[Vuex] fetchAllReminders error:', error);
        commit('SET_REMINDERS', []);
        return [];
      }
    },
    
    async createNewReminder({ commit, dispatch }, reminder) {
      try {
        if (!ipcRenderer || !ipcRenderer.invoke) {
          console.warn('[Vuex] createNewReminder: ipcRenderer not available');
          return false;
        }
        
        const result = await ipcRenderer.invoke('db-create-reminder', { reminder });
        if (result && result.success) {
          // 重新获取所有提醒，确保nextTriggerTimestamp等计算字段是最新的
          await dispatch('fetchAllReminders');
          return true;
        }
        return false;
      } catch (error) {
        console.error('[Vuex] createNewReminder error:', error);
        return false;
      }
    },
    
    async updateExistingReminder({ commit, dispatch }, reminder) {
      try {
        if (!ipcRenderer || !ipcRenderer.invoke) {
          console.warn('[Vuex] updateExistingReminder: ipcRenderer not available');
          return false;
        }
        
        const result = await ipcRenderer.invoke('db-update-reminder', { reminder });
        if (result && result.success) {
          // 重新获取所有提醒，确保nextTriggerTimestamp等计算字段是最新的
          await dispatch('fetchAllReminders');
          return true;
        }
        return false;
      } catch (error) {
        console.error('[Vuex] updateExistingReminder error:', error);
        return false;
      }
    },
    
    async deleteExistingReminder({ commit }, reminderId) {
      try {
        if (!ipcRenderer || !ipcRenderer.invoke) {
          console.warn('[Vuex] deleteExistingReminder: ipcRenderer not available');
          return false;
        }
        
        const result = await ipcRenderer.invoke('db-delete-reminder', { reminderId });
        if (result && result.success) {
          commit('DELETE_REMINDER', reminderId);
          return true;
        }
        return false;
      } catch (error) {
        console.error('[Vuex] deleteExistingReminder error:', error);
        return false;
      }
    },
    
    async toggleReminderActiveStatus({ commit }, { reminderId, isActive }) {
      try {
        if (!ipcRenderer || !ipcRenderer.invoke) {
          console.warn('[Vuex] toggleReminderActiveStatus: ipcRenderer not available');
          return false;
        }
        
        const result = await ipcRenderer.invoke('db-update-reminder-active', { 
          reminderId, 
          isActive 
        });
        
        if (result && result.success) {
          commit('SET_REMINDER_ACTIVE_STATUS', { reminderId, isActive });
          return true;
        }
        return false;
      } catch (error) {
        console.error('[Vuex] toggleReminderActiveStatus error:', error);
        return false;
      }
    },
  },
  getters: {
    formattedCurrentDateKey(state) {
      return getFormattedDateKey(state.currentDate);
    },
    todosForCurrentDate(state, getters) {
      if (!state.isDataLoaded && !state.todosByDate[getters.formattedCurrentDateKey]) {
        return [];
      }
      return state.todosByDate[getters.formattedCurrentDateKey] || [];
    },
    currentDateObject(state) {
      return state.currentDate;
    },
    isDataReady(state) {
      return state.isDataLoaded;
    },
    getInboxTodos(state) {
      return state.inboxTodos;
    },
    getArchivedTodos(state) {
      return state.archivedTodos;
    },
    archivedTodosLoadStatus(state) {
      return state.archivedTodosLoaded;
    },
    // Getter for settings
    appSettings(state) {
      return state.settings;
    },
    // 新增：获取数据库使用状态
    usingSqlite(state) {
      return state.useSqlite;
    },
    getAllReminders(state) {
      return state.reminders;
    },
    remindersLoadStatus(state) {
      return state.remindersLoaded;
    },
  },
  modules: {
  }
});

// 设置初始化debounced函数以保存数据
debouncedSaveAllData = debounce(() => {
  store.dispatch('saveAllDataToDisk');
}, 1000); // 1秒延迟防止频繁写入

// 过早调用triggerSaveData会导致错误，因为此时store还未完全初始化
// store.dispatch('triggerSaveData', null, { root: true });

// Listen for theme changes from main process (e.g., native theme or menu triggered)
if (ipcRenderer && typeof ipcRenderer.on === 'function') {
  ipcRenderer.on('theme-changed-externally', (event, newTheme) => { // Electron IPC listeners usually pass 'event' as first arg
    console.log(`[Vuex] Received 'theme-changed-externally' from main: ${newTheme}`);
    // Use updateSettingsInternal to prevent re-notifying main and apply to DOM
    store.dispatch('updateSettingsInternal', { theme: newTheme });
  });

  // REMOVED: The direct listener for 'toggle-mini-mode' in store was already commented out.
  // App.vue will handle the 'toggle-mini-mode' IPC from main and use 'updateSettingsInternal'.
  }

// It might also be part of a plugin or store setup function, like:
// setupIPCListeners(storeInstance) {
//   ipcRenderer.on('toggle-mini-mode', (event, newMiniModeState) => {
//      storeInstance.commit('UPDATE_SETTINGS', { miniMode: newMiniModeState });
//   });
// }
// If such a function exists and is called, the listener inside it should be commented out.

export default store; 